﻿using AutoStar.Common;
using AutoStar.Models;
using AutoStar.Views;
using GalaSoft.MvvmLight.CommandWpf;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Configuration;
using System.IO.Ports;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Remoting.Channels;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Input;

namespace AutoStar.ViewModel
{
    public class PrintChannelVM : BaseViewModel
    {
        public PrintChannelVM()
        {
            Init();
        }
        private LowTemperatureModule _lowTemperatureModule;
        public PrintChannelVM(LowTemperatureModule lowTemperatureModule)
        {
            //ModuleCommand = new RelayCommand(ModuleCommand_Execute);
            _lowTemperatureModule = lowTemperatureModule;
            Init();
        }


        public void Init()
        {
            try
            {
                int count = Global.printProject.printChannels.Count(); 
                Group1ViewModels = new ObservableCollection<PrinChannelModel>[7];
                for (int i = 0; i < count; i++)
                {
                    var channel = Global.printProject.printChannels[i];
                    Group1ViewModels[i] = new ObservableCollection<PrinChannelModel>();
                    var model = new PrinChannelModel
                    {
                        text21 = channel.AirPress,
                        text22 = Math.Round(channel.Temperature, 1),
                        text23 = channel.PrintSpeed / 60,
                        text24 = channel.T1,
                        text25 = channel.T2,
                        text26 = channel.T3,
                        text27 = Math.Round(channel.position.X, 2),
                        text28 = Math.Round(channel.position.Y, 2),
                    };
                    Group1ViewModels[i].Add(model);
                }
                for (int i = 0; i < count; i++)
                {
                    string propertyName = "Group" + i + "Header";
                    string header = "通道" + (i + 1) + "----";
                    PropertyInfo propertyInfo = this.GetType().GetProperty(propertyName);
                    if (propertyInfo != null)
                        propertyInfo.SetValue(this, header + Global.printProject.printChannels[i].ChannelType);
                }
                //默认通道1
                Group1ViewModel = Group1ViewModels[0];

                ModeList = new ObservableCollection<string>()
            {
                "持续挤出","快速设置"
            };
                SelectedChannel = 0;
                ModifyCommand = new RelayCommand(ModifyCommand_Execute);
            }
            catch (Exception ex)
            {

            }
        }

        public void SetHeader()
        {
            for (int i = 0; i < 8; i++)
            {
                string propertyName = "Group" + i + "Header";
                string header = "通道" + (i + 1) + "----";
                PropertyInfo propertyInfo = this.GetType().GetProperty(propertyName);
                if (propertyInfo != null)
                    propertyInfo.SetValue(this, header + Global.printProject.printChannels[i].ChannelType);
            }
        }
        private void ModifyCommand_Execute()
        {
            try
            {
                if (Global.printProject.printChannels[SelectedChannel].ChannelType.Contains("降温"))
                {
                    if (Group1ViewModel[0].text22 < 8 || Group1ViewModel[0].text22 > 20)
                    {
                        MessageBox.Show("低温温度范围8-20");
                        return;
                    }
                }
                //ExecuteModifyCommand();
                if ((Global.printProject.printChannels[SelectedChannel].ChannelType.Contains("降温")
                    || Global.printProject.printChannels[SelectedChannel].ChannelType.Contains("升温"))
                    && !IsTrueTemperatureCtrl)
                {
                    MainWindow.printer.SendGCode("M262"); // 温度控制打开
                    IsTrueTemperatureCtrl = true;
                }
                if (SelectedChannel == 0)
                    Group1ViewModels[0] = Group1ViewModel;
                else if (SelectedChannel == 1)
                    Group1ViewModels[1] = Group1ViewModel;
                else if (SelectedChannel == 2)
                    Group1ViewModels[2] = Group1ViewModel;
                else if (SelectedChannel == 3)
                    Group1ViewModels[3] = Group1ViewModel;
                else if (SelectedChannel == 4)
                    Group1ViewModels[4] = Group1ViewModel;
                else if (SelectedChannel == 5)
                    Group1ViewModels[5] = Group1ViewModel;
                else if (SelectedChannel == 6)
                    Group1ViewModels[6] = Group1ViewModel;
                else if (SelectedChannel == 7)
                    Group1ViewModels[7] = Group1ViewModel;
                
                // Group1ViewModel可能存在类型转换问题，实际调试中关注
                Global.printProject.printChannels[SelectedChannel].AirPress = Convert.ToDouble(Group1ViewModel[0].text21);
                Global.printProject.printChannels[SelectedChannel].Temperature = Convert.ToDouble(Group1ViewModel[0].text22);
                Global.printProject.printChannels[SelectedChannel].PrintSpeed = Convert.ToDouble(Group1ViewModel[0].text23 * 60);
                Global.printProject.printChannels[SelectedChannel].T1 = Convert.ToDouble(Group1ViewModel[0].text24);
                Global.printProject.printChannels[SelectedChannel].T2 = Convert.ToDouble(Group1ViewModel[0].text25);
                Global.printProject.printChannels[SelectedChannel].T3 = Convert.ToDouble(Group1ViewModel[0].text26);
                Global.printProject.printChannels[SelectedChannel].position.X = (float)Convert.ToDouble(Group1ViewModel[0].text27);
                Global.printProject.printChannels[SelectedChannel].position.Y = (float)Convert.ToDouble(Group1ViewModel[0].text28);
                //动态气压 温度
                Global.MainViewVM.CurrentPressure = Global.printProject.printChannels[SelectedChannel].AirPress.ToString();
                //Global.MainViewVM.CurrentTemperature = Global.printProject.printChannels[SelectedChannel].Temperature.ToString();

                //短暂存放
                if (Global.printProject.printChannels[SelectedChannel].ChannelType.Contains("降温") && IsTrueTemperatureCtrl)
                    Global.MainViewVM.LowTemperature = Global.printProject.printChannels[SelectedChannel].Temperature.ToString();
                else if (Global.printProject.printChannels[SelectedChannel].ChannelType.Contains("升温") && IsTrueTemperatureCtrl)
                    Global.MainViewVM.Temperature = Global.printProject.printChannels[SelectedChannel].Temperature.ToString();
                //else if((Global.printProject.printChannels[SelectedChannel].ChannelType.Contains("降温") 
                //    || Global.printProject.printChannels[SelectedChannel].ChannelType.Contains("升温"))
                //    && ModuleValue.Equals("打开低温控制"))
                //{
                //    MessageBox.Show("请打开温度控制！");
                //    return;
                //}


                //Global.MainVM.setChannel(Global.printProject.printChannels[SelectedChannel].ChannelID);
                Global.MainVM.setChannel(SelectedChannel);
                if (SelectedMode != 0)
                {
                    Global.printProject.printChannels.Add(new PrintChannel());
                    int tempChannel = Global.printProject.printChannels.Count - 1;
                    Global.MainVM.setChannel(tempChannel);
                    Global.printProject.printChannels.RemoveAt(tempChannel);
                }
                List<ChannelList> channels = new List<ChannelList>
            {
                new ChannelList { Name = "通道1", Parameters = new PrinChannelModel() },
                new ChannelList { Name = "通道2", Parameters = new PrinChannelModel() },
                new ChannelList { Name = "通道3", Parameters = new PrinChannelModel() },
                new ChannelList { Name = "通道4", Parameters = new PrinChannelModel() },
                new ChannelList { Name = "通道5", Parameters = new PrinChannelModel() },
                new ChannelList { Name = "通道6", Parameters = new PrinChannelModel() },
                new ChannelList { Name = "通道7", Parameters = new PrinChannelModel() }
                //new ChannelList { Name = "调试通道", Parameters = new PrinChannelModel() }
            };
                for (int i = 0; i < Global.printProject.printChannels.Count; i++)
                {
                    channels[i].Parameters.text21 = Global.printProject.printChannels[i].AirPress;
                    channels[i].Parameters.text22 = Global.printProject.printChannels[i].Temperature;
                    channels[i].Parameters.text23 = Global.printProject.printChannels[i].PrintSpeed / 60;
                    channels[i].Parameters.text24 = Global.printProject.printChannels[i].T1;
                    channels[i].Parameters.text25 = Global.printProject.printChannels[i].T2;
                    channels[i].Parameters.text26 = Global.printProject.printChannels[i].T3;
                    channels[i].Parameters.text27 = Global.printProject.printChannels[i].position.X;
                    channels[i].Parameters.text28 = Global.printProject.printChannels[i].position.Y;
                }
                UpdateConfigFile(channels);
            }
            catch (Exception ex)
            {
                Global.LogHelper.WriteLog(ex.ToString());
            }
        }
        private void UpdateChannel()
        {
            if (SelectedChannel == 0)
                Group1ViewModel = Group1ViewModels[0];
            else if (SelectedChannel == 1)
                Group1ViewModel = Group1ViewModels[1];
            else if (SelectedChannel == 2)
                Group1ViewModel = Group1ViewModels[2];
            else if (SelectedChannel == 3)
                Group1ViewModel = Group1ViewModels[3];
            else if (SelectedChannel == 4)
                Group1ViewModel = Group1ViewModels[4];
            else if (SelectedChannel == 5)
                Group1ViewModel = Group1ViewModels[5];
            else if (SelectedChannel == 6)
                Group1ViewModel = Group1ViewModels[6];
            //else if (SelectedChannel == 7)
            //    Group1ViewModel = Group1ViewModels[7];
        }
        public void UpdateConfigFile(List<ChannelList> channels)
        {
            try
            {
                Configuration config = Global.config;

                for (int i = 0; i < channels.Count; i++)
                {
                    // 在这里对PrintSpeed进行除以60的操作
                    channels[i].Parameters.text23 = channels[i].Parameters.text23 * 60;

                    string channelData = JsonConvert.SerializeObject(channels[i].Parameters);
                    string encryptedText = Global.encryption.Encrypt(channelData);
                    string key = "Channel" + (i + 1);
                    if (config.AppSettings.Settings[key] != null)
                        config.AppSettings.Settings[key].Value = encryptedText;
                    else
                        config.AppSettings.Settings.Add(key, encryptedText);
                }
                config.Save(ConfigurationSaveMode.Modified);
                ConfigurationManager.RefreshSection("appSettings");
            }
            catch
            {
            }
        }
        private double GetValueFromChannel(ChannelList channel, int paramIndex)
        {
            switch (paramIndex)
            {
                case 1:
                    return channel.Parameters.text21;
                case 2:
                    return channel.Parameters.text22;
                case 3:
                    return channel.Parameters.text23;
                case 4:
                    return channel.Parameters.text24;
                case 5:
                    return channel.Parameters.text25;
                case 6:
                    return channel.Parameters.text26;
                case 7:
                    return channel.Parameters.text27;
                case 8:
                    return channel.Parameters.text28;
                default:
                    return 0;
            }
        }
        private void ExecuteModifyCommand()
        {
            try
            {

                if (Global.SettingVM.channels[SelectedChannel].SelectedCategory.Contains("降温"))
                {
                    string instruction = "TC1:TCADJTEMP=" + Group1ViewModel[0].text22;
                    Global.LogHelper.WriteLog("降温通道if：" + instruction);
                    string returnStr = Global.SettingVM._lowTemperatureModule.SendCommand(instruction);
                    Global.LogHelper.WriteLog("接收降温回传：" + returnStr);
                }
                else
                {
                    // 其他逻辑处理
                }
            }
            catch (Exception ex)
            {
                Global.LogHelper.WriteLog(ex.ToString());
            }
        }
        private void ParseResponse(string response)
        {
            // 解析回传的数据
        }
        public bool IsTrueTemperatureCtrl = false;
        //private void ModuleCommand_Execute()
        //{
        //    if (ModuleValue.Equals("打开低温控制"))
        //    {
        //        MainWindow.printer.SendGCode("M262");
        //        ModuleValue = "关闭低温控制";
        //    }
        //    else if (ModuleValue.Equals("关闭低温控制"))
        //    {
        //        MainWindow.printer.SendGCode("M263");
        //        ModuleValue = "打开低温控制";
        //    }
        //}

        //public ICommand ModuleCommand { get; private set; }
        //private string _ModuleValue = "打开低温控制";
        //public string ModuleValue
        //{
        //    get => _ModuleValue;
        //    set => Set(ref _ModuleValue, value);
        //}
        public ICommand ModifyCommand { get; set; }
        private int _SelectedChannel;
        public int SelectedChannel
        {
            get => _SelectedChannel;
            set
            {
                if (_SelectedChannel == value) return; // 避免不必要的更新  
                _SelectedChannel = value;
                UpdateChannel();
                Set(ref _SelectedChannel, value);
            }
        }
        private ObservableCollection<string> _ChannelList = new ObservableCollection<string>()
            {
                "通道1","通道2","通道3","通道4","通道5","通道6","通道7"/*,"调试通道"*/
            };
        public ObservableCollection<string> ChannelList
        {
            get => _ChannelList;
            set => Set(ref _ChannelList, value);
        }

        private int _SelectedMode;
        public int SelectedMode
        {
            get => _SelectedMode;
            set => Set(ref _SelectedMode, value);
        }
        private ObservableCollection<string> _ModeList;
        public ObservableCollection<string> ModeList
        {
            get => _ModeList;
            set => Set(ref _ModeList, value);
        }
        private ObservableCollection<PrinChannelModel> _Group1ViewModel;
        public ObservableCollection<PrinChannelModel> Group1ViewModel
        {
            get => _Group1ViewModel;
            set => Set(ref _Group1ViewModel, value);
        }
        private string _Group1Header;
        public string Group1Header
        {
            get => _Group1Header;
            set => Set(ref _Group1Header, value);
        }
        private string _Group2Header;
        public string Group2Header
        {
            get => _Group2Header;
            set => Set(ref _Group2Header, value);
        }
        private string _Group3Header;
        public string Group3Header
        {
            get => _Group3Header;
            set => Set(ref _Group3Header, value);
        }
        private string _Group4Header;
        public string Group4Header
        {
            get => _Group4Header;
            set => Set(ref _Group4Header, value);
        }
        private string _Group5Header;
        public string Group5Header
        {
            get => _Group5Header;
            set => Set(ref _Group5Header, value);
        }
        private string _Group6Header;
        public string Group6Header
        {
            get => _Group6Header;
            set => Set(ref _Group6Header, value);
        }
        private string _Group0Header;
        public string Group0Header
        {
            get => _Group0Header;
            set => Set(ref _Group0Header, value);
        }
        public ObservableCollection<PrinChannelModel>[] Group1ViewModels { get; set; }
    }
}
